import React, { Component } from 'react'
import "./index.css";
import axios from "axios";
import $ from 'jquery';

import { NavBar,WingBlank,List,InputItem,Icon,Grid,Toast } from "antd-mobile";

import { getChatId } from "../../common/getChatId";

import { connect } from "react-redux";
import { loadUseinfoData } from '../../redux/reducers/user.reducer.js';
import { getChats, resvChat, initChatListAction, markReadChat } from '../../redux/reducers/chat.reducer.js';

import io from "socket.io-client";
const socket = io('ws://localhost:3001');
socket.on('res_msg',(data)=>{
    // this.getInitChats();
    // Chat.getInitChats0();
})

class Chat extends Component {
    constructor(props){
        super(props);
        this.state = {
            input_value:'',
            msgData:[],
            to_name:'',
            to_avatar:'',
            my_avatar:'',
            chat_id:'',
            emojiShow:false
        }
        this.emojiToggleClick = this.emojiToggleClick.bind(this);
    }
    
    render() {
        const emoji = `😃 😀 😊 😂 🤣 😄 🤮 😍 🤧 🤔 🙃 😀 😉 😇 😘 😚 😋 😛 🤪 🤐 🤨 😶 😪 😔 🙄 😏 😷 🤢 😵 🤯 😰 😨 😱 😡 🤬 😈 😸 😹 👌 🤞 👍 💪 👨‍ 👩‍ 🙋`
        .split(" ")
        .filter(item => item)
        .map(emo => ({text:emo}))
        const toUserId = this.props.match.params.userId;
        const filterChats = this.props.Chats.chats.filter(chat=>{
            return chat.chat_id === this.state.chat_id
        })
        if(!this.state.to_avatar){
            return null
        }
        return (
            <div className="chat_wrapper">
                 <div className="head_box">
                    <NavBar mode="dark"
                        icon={<Icon type="left" />}
                        onLeftClick={() => this.props.history.goBack()}
                     >{this.state.to_name}</NavBar>
                </div>
                
                {/* 聊天区域  {}中坚决不能是对象做显示*/}
                <div className={`chat_content_box ${this.state.emojiShow === true ? "emoji_show_class" : ""}`} id="scroll_id">
                    <WingBlank>
                        {filterChats.map((item,index)=>{
                            return toUserId===item.to?
                                (<div className="myself_box" key={index}> 
                                    <div className="free_box"></div>
                                    <div className="chat my_chat">{item.chat}{item.avatar}</div>
                                    <img src={require('../../assets/img/'+this.state.my_avatar+'.png')} alt='' className="chat_img my_avatar"/>
                                </div>):
                                (<div className="other_box" key={index}>
                                    {/* <img src={require('../../assets/img/avatar6.png')} alt='' className="chat_img"/> */}
                                    <img src={require('../../assets/img/'+this.state.to_avatar+'.png')} alt='' className="chat_img"/>
                                    <div className="chat">{item.chat}</div>
                                </div>)
                        })}
                    </WingBlank>
                </div>

                {/* 发送 */}
                <div className="send_box">
                   <List>
                       <InputItem
                            placeholder="请输入"
                            value={this.state.input_value}
                            onChange={(val) => this.inputChang('input_value',val)}
                            extra={
                                <div>
                                    <span className="emojji_img" onClick={this.emojiToggleClick}>😄</span>
                                    <span onClick={()=>this.senClick()}>发送</span>
                                </div>
                            }
                            ></InputItem>
                   </List>
                   {
                       this.state.emojiShow?
                       <Grid
                        data={emoji}
                        columnNum={9}
                        carouselMaxRow={4}
                        isCarousel={true}
                        onClick={(el)=>this.emojiClick(el)}
                        ></Grid>:null
                   }
                </div>
            </div>
        )
    }

    
    componentDidMount(){
        this.props.loadUseinfoData();
        if(!this.props.Chats.chats.length){
            this.getInitChats0();
            socket.on('res_msg',(data)=>{
                this.props.resvChat(data);
            })
        }
        const to_id = this.props.match.params.userId;
        const users = this.props.Chats.users;
        const from_id = this.props.Users._id;
        this.setState({
            to_name:users[to_id].name,
            to_avatar:users[to_id].avatar,
            my_avatar:this.props.Users.avatar,
            chat_id:getChatId(from_id,to_id)
        })
       this.resizeStyle();
       this.markChatRead(to_id,from_id);
       $("#scroll_id").scrollTop(5000);
    }

    componentWillUnmount(){
        const to_id = this.props.match.params.userId;
        const from_id = this.props.Users._id;
        // 消息标为已读
        this.markChatRead(to_id,from_id);
    }

    resizeStyle(){
         // 表情包样式
         setTimeout(()=>{
            window.dispatchEvent(new Event('resize'))
        },0)
    }
    markChatRead(to_id,from_id){
        axios.post('/chatapi/read',{toId:to_id}).then(res=>{
            if(res.state===200&&res.data.code===0){
                let read_num = res.data.readnum;
                this.props.markReadChat(to_id,from_id,read_num);
            }
        })
    }
    // 方法一
    getInitChats(){
        let fromId = this.props.Users._id;
        this.props.getChats(fromId);
    }
    // 方法二
    getInitChats0(){
        let fromId = this.props.Users._id;
        axios.get('/chatapi/chatlist').then(res=>{
            if(res.status === 200){
                if(res.data.code===0){
                    this.props.initChatListAction(res.data.data,res.data.users,fromId);
                }
            }
        });
    }
    inputChang(key,val){
        this.setState({
            [key]:val
        })
    }
    emojiToggleClick(){
        this.resizeStyle();
        this.setState({
            emojiShow:!this.state.emojiShow
        })
    }
    emojiClick(el){
        this.setState({
            input_value:this.state.input_value + el.text
        })
    }
    senClick(){
        let from = this.props.Users._id;
        let to = this.props.match.params.userId;
        let chat = this.state.input_value;
        if(!chat){
            Toast.fail('请输入内容', 1);
            return false;
        }
        // 输入值主动emit send_mgs
        socket.emit('send_msg',{from,to,chat});
        this.setState({
            input_value:''
        });
        // 监听data传过来
        socket.on('res_msg',(data)=>{
            // this.getInitChats();
            this.getInitChats0();
        })
        // 滚动条
        this.scrollToBottom();
    }
    scrollToBottom(){
        $("#scroll_id").scrollTop($("#scroll_id")[0].scrollHeight+5000);
    }
}

const mapStateToProps = (state,props)=> {
    return {
        Users:state.userReducer,
        Chats:state.chatReducer
    }
}

export default connect(mapStateToProps,{
    getChats,
    resvChat,
    markReadChat,
    initChatListAction,
    loadUseinfoData
})(Chat);